package p2pcdnsim.network;

import java.util.LinkedList;
import java.util.List;

import desmoj.core.simulator.SimTime;

public class DatagramSocket {

	private int port;
	private ApplicationProcess applicationProcess;
	private TransportLayer transportLayer;
	private List<DatagramPacket> datagrams;
	
	private DatagramPacket toReturn;

	public DatagramSocket(TransportLayer transportLayer,ApplicationProcess applicationProcess,int port) {
		this.applicationProcess = applicationProcess;
		this.transportLayer = transportLayer;
		this.port = port;
		datagrams = new LinkedList<DatagramPacket>();
		toReturn = null;
	}

	public DatagramPacket receive() {
		if(datagrams.size()!=0) return datagrams.remove(0);
		toReturn = null;
		applicationProcess.passivate();
		return toReturn;

	}
	
	
	private void setReturnPacket(DatagramPacket d) {
		this.toReturn = d;
		if(!applicationProcess.isScheduled()) applicationProcess.activate(new SimTime(0));
	}

	public void receiveDatagramPacket(DatagramPacket content) {
		datagrams.add(content);
		if(toReturn == null) this.setReturnPacket(datagrams.remove(0));
	}

	public int getPort() {
		return port;
	}

	public NetworkAddress getAddress() {
		return applicationProcess.getNetworkAddress();
	}

	public void send(DatagramPacket packet) {
		applicationProcess.getApplicationLayer().getTransportLayer().transmitDatagram(packet, applicationProcess.currentTime());
	}
	
	public void close() {
		transportLayer.close(this);
	} 
}
